const httpUtils = require('./httpUtils.js')
/**
 * 上传单个文件封装
 * @param url 上传地址
 * @param filePath 文件路径
 * @param formData HTTP请求中其他额外的 form data
 * @param name 文件对应的key
 * @param success  成功回调
 * @param fail 失败回调
 */
function uploadFile(url, filePath, formData, name, success, fail) {
  wx.uploadFile({
    url: getApp().globalData.baseUrl + url,
    filePath: filePath,
    name: name,
    formData: formData,
    success: function (res) {
      var data = res.data
      console.log(data)
      typeof success == "function" && success(res.data)
      //do something
    },
    fail: function (res) {
      console.log(res)
      typeof fail == "function" && fail(res)
    }
  })
}

/**
 * 上传多个文件封装
 * @param urls 上传地址
 * @param filePaths 文件路径
 * @param formDatas HTTP请求中其他额外的 form data
 * @param names 文件对应的key
 * @param success  成功回调
 * @param fail 失败回调
 */

function uploadFiles(filePaths, successUp, failUp, i, success, fail) {
  console.log("upload filePath", filePaths, getApp().globalData.baseUrl)
  let length = filePaths.length;
  let filePath = filePaths[i] + '';
  if (length == 0) {
    return success(filePaths);
  }
  if (filePath.indexOf(getApp().globalData.sourceUrl) != -1){
    if (i == length-1) {
      if (failUp == 0) {
        success(filePaths);
      } else {
        fail();
      }
    } else {
      i++;
      return uploadFiles(filePaths, successUp, failUp, i, success, fail);
    }
  } else {
    if (i == 0) {
      wx.showLoading({
        title: '正在上传',
      });
    }
    wx.uploadFile({
      url: getApp().globalData.baseUrl + getApp().api.upload_file,
      filePath: filePath,
      name: 'files',
      method: 'POST',
      header: {
        "Content-type": 'multipart/form-data',
        "token": getApp().globalData.token
      },
      success: function (res) {
        if (res.statusCode == 200) {
          successUp++;
          var data = res.data
          console.log("success==================",data)
          filePaths[i] = JSON.parse(data).filePaths[0].filePath;
        } else {
          failUp++;
        }
      },
      fail: function (res) {
        failUp++;
        console.log("fail==================", res)
      },
      complete: function (res) {
        console.log("complete==================", res)
        i++;
        if (i == length) {
          wx.hideLoading();
          if (failUp == 0) {
            // wx.showToast({
            //   title: '上传成功',
            //   duration: 2000,
            //   icon: 'success'
            // })
            // 成功回调
            typeof success == "function" && success(filePaths);
          } else {
            // 失败回调
            typeof fail == "function" && fail();
          }
          console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
        } else {
          return uploadFiles(filePaths, successUp, failUp, i, success, fail);
        }
      }
    })
  }
}

/** 
 * 函数描述：作为上传文件时递归上传的函数体； 
 * filePaths是文件路径数组
 * successUp是成功上传的个数
 * failUp是上传失败的个数
 * i是文件路径数组的指标
 * success上传成功后回调
 * failed上传失败后回调
 */

function uploadMultFiles(uploadUrl, filePaths, formData, successUp, failUp, i, successCallBack, failedCallBack) {
  let that = this;
  if (i == 0) {
    wx.showLoading({
      title: '正在上传',
    });
  }
  wx.uploadFile({
    url: getApp().globalData.baseUrl + uploadUrl,
    filePath: filePaths[i],
    name: 'files',
    method: 'POST',
    formData: formData,
    header: {
      "Content-type": 'multipart/form-data',
      "token": getApp().globalData.token
    },
    success: (resp) => {
      successUp++;
    },
    fail: (res) => {
      failUp++;
    },
    complete: () => {
      i++;
      // 图片递归完成
      if (i == filePaths.length) {
        wx.hideLoading();
        if (i == successUp) {
          // wx.showToast({
          //   title: '上传成功',
          //   duration: 2000,
          //   icon: 'none'
          // })
          // 成功回调
          successCallBack();
        } else {
          // 失败回调
          failedCallBack();
        }
        console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
      }
      else {  //递归调用uploadDIY函数
        return uploadMultFiles(uploadUrl, filePaths, formData, successUp, failUp, i, successCallBack, failedCallBack);
      }
    },
  });
}

/**
 * 封装下载一个文件并且保存文件
 * @param id 需要下载文件的id
 * @param url 下载文件的网络地址
 * @param success  成功回调
 * @param fail 失败回调
 */

function downloadSaveFile(id, url, success, fail) {
  let that = this;
  wx.downloadFile({
    url: url,
    success: function (res) {
      wx.saveFile({
        tempFilePath: res.tempFilePath,
        success: function (result) {
          result.id = id;
          if (success) {
            success(result);
          }
        },
        fail: function (e) {
          console.info("保存一个文件失败");
          if (fail) {
            fail(e);
          }
        }
      })

    },
    fail: function (e) {
      console.info("下载一个文件失败");
      if (fail) {
        fail(e);
      }

    }
  })
}

/**
 * 封装下载多文件并且保存文件
 * @param urls 下载文件的网络地址
 * @param success  成功回调
 * @param fail 失败回调
 */
function downloadSaveFiles(urls, success, fail) {
  let that = this;
  let savedFilePaths = new Map();
  let urlsLength = urls.length;  // 有几个url需要下载

  for (let i = 0; i < urlsLength; i++) {
    downloadSaveFile({
      url: urls[i],
      success: function (res) {
        //console.dir(res);
        //一个文件下载保存成功
        let savedFilePath = res.savedFilePath;

        savedFilePaths.set(res.id, res);
        console.info("savedFilePath:%s", savedFilePath);
        if (savedFilePaths.size == urlsLength) { //如果所有的url 才算成功
          if (success) {
            success(savedFilePaths)
          }

        }
      },
      fail: function (e) {
        console.info("下载失败");
        if (fail) {
          fail(e);
        }

      }
    })

  }

}
module.exports = {
  uploadFile: uploadFile,
  uploadFiles: uploadFiles,
  uploadMultFiles: uploadMultFiles,
  downloadSaveFile: downloadSaveFile,
  downloadSaveFiles: downloadSaveFiles
}